package com.zrrd.gmall.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zrrd.gmall.cart.feign.CartFeignClient;
import com.zrrd.gmall.common.util.HttpClientUtil;
import com.zrrd.gmall.model.enums.OrderStatus;
import com.zrrd.gmall.model.enums.ProcessStatus;
import com.zrrd.gmall.model.order.OrderDetail;
import com.zrrd.gmall.model.order.OrderInfo;
import com.zrrd.gmall.order.mapper.OrderDetailMapper;
import com.zrrd.gmall.order.mapper.OrderInfoMapper;
import com.zrrd.gmall.order.service.OrderService;
import com.zrrd.gmall.rabbit.constant.MqConstant;
import com.zrrd.gmall.rabbit.service.RabbitService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
public class OrderServiceImpl extends ServiceImpl<OrderInfoMapper, OrderInfo> implements OrderService {
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private RabbitService rabbitService;
    @Override
    @Transactional
    public Long saveOrderInfo(OrderInfo orderInfo) {
        //计算总金额
        orderInfo.sumTotalAmount();
        //设置状态
        orderInfo.setOrderStatus(OrderStatus.UNPAID.name());
        //设置订单编号
        String outTradeNo = "zrrd"+System.currentTimeMillis()+""+new Random().nextInt(1000);
        orderInfo.setOutTradeNo(outTradeNo);
        orderInfo.setCreateTime(new Date());
        //奢姿过期时间
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE,1);
        orderInfo.setExpireTime(calendar.getTime());
        //订单进度
        orderInfo.setProcessStatus(ProcessStatus.UNPAID.name());
        //设置订单的描述 为每一个商品名称的拼接
        List<OrderDetail> orderDetailList = orderInfo.getOrderDetailList();
        StringBuilder tradeBody = new StringBuilder();
        for (OrderDetail detail : orderDetailList) {
            tradeBody.append(detail.getSkuName()+" ");
        }
        if (tradeBody.toString().length()>100){
            orderInfo.setTradeBody(tradeBody.toString().substring(0,100));
        }else {
            orderInfo.setTradeBody(tradeBody.toString());
        }
        this.save(orderInfo);
        //遍历订单明细
        for (OrderDetail detail : orderDetailList){
            //设置ID
            detail.setOrderId(orderInfo.getId());
            //保存订单明细
            orderDetailMapper.insert(detail);
        }
        //发送延迟消息

        rabbitService.sendDelayMessage(MqConstant.EXCHANGE_DIRECT_ORDER_CANCEL,
                MqConstant.ROUTING_ORDER_CANCEL,
                orderInfo.getId(),
                MqConstant.DELAY_TIME);
        System.out.println("发送延迟消息====>"+orderInfo.getId());


        return orderInfo.getId();
    }

    @Override
    public String getTradeNo(String userId) {
        String tradeNo = UUID.randomUUID().toString().replace("-","");
        //存入redis
        redisTemplate.opsForValue().set(this.getNoKey(userId),tradeNo);
        //返回流水号
        return tradeNo;
    }

    @Override
    public boolean checkTradeNo(String userId, String tradeNo) {
        //从Redis中获得流水号
        String tradeCacheNo = (String) redisTemplate.opsForValue().get(this.getNoKey(userId));
        //返回比较结果
        return tradeNo.equals(tradeCacheNo);
    }

    @Override
    public void deleteTradeNo(String userId) {
        //从Redis中删除流水号
        redisTemplate.delete(this.getNoKey(userId));
    }
    //检查库存的方法
    @Override
    public boolean checkStock(Long skuId, Integer skuNum) {
        System.out.println("检查库存====>");
        System.out.println(skuId);
        System.out.println(skuNum);
        //远程调用库存
        String result = HttpClientUtil.doGet("http://localhost:9001/hasStock?skuId=" + skuId + "&num=" + skuNum);
        System.out.println("检验结果===>"+result);
        return "1".equals(result);
    }
    //更新订单状态
    @Override
    public void updateOrderStatus(Long orderId,ProcessStatus processStatus) {
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setId(orderId);
        orderInfo.setProcessStatus(processStatus.name());
        orderInfo.setOrderStatus(processStatus.getOrderStatus().name());
        this.updateById(orderInfo);
    }

    @Override
    public OrderInfo getOrderInfo(Long orderId) {
        OrderInfo orderInfo = this.getById(orderId);
        QueryWrapper<OrderDetail> wrapper = new QueryWrapper<>();
        wrapper.eq("order_id",orderId);
        List<OrderDetail> orderDetailList = orderDetailMapper.selectList(wrapper);
        orderInfo.setOrderDetailList(orderDetailList);
        return orderInfo;
    }

    //redis方法
    public String getNoKey(String userId){
        return "user:"+ userId + ":tradeNo";
    }
}
